package com.yqd.lesson.actor.four

import scala.concurrent.duration._
import akka.actor.{Actor, ActorIdentity, ActorLogging, ActorRef, Identify, Props, ReceiveTimeout, Terminated}
import com.yqd.lesson.actor.four.Receiver.Greeting



object Sender{
  def props(path:String): Props = Props(new Sender(path))
}

class Sender(path:String) extends Actor with ActorLogging{


  //Identify消息，所有actor会理解它并自动返回一个包
  sendIdentifyRequest()

  def sendIdentifyRequest(): Unit = {
    context.actorSelection(path) ! Identify(path)
    import context.dispatcher
    context.system.scheduler.scheduleOnce(3.seconds, self, ReceiveTimeout)
  }


  override def receive: Receive = {
    case ActorIdentity(`path`, Some(actor)) =>
      //监视watch()
      context.watch(actor)
      //更换actor的receive
      context.become(active(actor))
    case ActorIdentity(`path`, None) => println(s"Remote actor not available: $path")
    case ReceiveTimeout              => {
      sendIdentifyRequest()}
    case _                           => println("Not ready yet")
  }

  def active(actor: ActorRef): Actor.Receive = {
    case greeting:String => actor ! Greeting(greeting)
    case Terminated(`actor`) =>
      println("receiver terminated")
      context.become(receive)
      context.unwatch(actor)
      sendIdentifyRequest()
    case ReceiveTimeout =>
      println("receiver timeout")
    // ignore

  }
}
